package request

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
	"unicode/utf8"
	"vector/tools"
)

func init() {
	_ = os.Mkdir("cache", 0755)
}

type TTStudio struct {
	txt        string
	isPlay     bool
	_speaker   map[string]string
	resultData map[string]any
}

func (T *TTStudio) Reset() {
	T.txt = ""
	T.isPlay = false
	clear(T.resultData)
	clear(T._speaker)
}

func (T *TTStudio) NewTaskData(row map[string]any) error {
	if txt, ok := row["话术"]; ok {
		T.txt = txt.(string)
	} else {
		T.resultData["备注"] = "参数错误"
		return fmt.Errorf("参数错误")
	}
	T.resultData = map[string]any{
		"话术":        T.txt,
		"spendTime": 0,
		"备注":        "",
		"pcm":       "",
		"total":     utf8.RuneCountInString(T.txt),
	}
	return nil
}

func (T *TTStudio) Do() {
	// 构建请求参数
	payload := map[string]any{
		//"txt": T.txt,
		//"speaker": _speaker,
		"endFlag": true,
		"sessionParam": map[string]any{
			"volume":            "10",
			"native_voice_name": "yezi",
			"sample_rate":       "16000",
			"pitch":             "0",
			"speed":             "0",
			"sid":               "e10ee582b5534029bfc6a812d512c719",
		},
		"text": T.txt,
	}
	body, _ := json.Marshal(payload)

	startTime := time.Now()
	// 发送请求
	response, err := http.Post(
		//"http://172.31.205.27:30326/vcs-open-api/tts/systhesis",
		"http://172.29.230.176:10011/createRec",
		"application/json",
		bytes.NewReader(body),
	)
	T.resultData["spendTime"] = time.Since(startTime).Milliseconds()
	if err != nil {
		T.resultData["备注"] = "http请求异常:" + err.Error()
		return
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		T.resultData["备注"] = "http响应异常:" + response.Status
		return
	}

	jsonData, err := io.ReadAll(response.Body)
	if err != nil {
		T.resultData["备注"] = "http响应异常:" + err.Error()
		return
	}

	var audioData []byte
	for _, bs64 := range strings.Split(string(jsonData), "\n") {
		bs64 = strings.TrimSpace(bs64)
		if bs64 == "" {
			continue
		}
		var resp map[string]any
		if err = json.Unmarshal([]byte(bs64), &resp); err != nil {
			T.resultData["备注"] = "http响应解析异常:" + err.Error()
			return
		}
		// 提取音频base64数据
		audioBase64 := resp["result"].(map[string]any)["data"].(string)

		// Base64解码
		d, err := base64.StdEncoding.DecodeString(audioBase64)
		if err != nil {
			T.resultData["备注"] = "音频base64数据异常:" + err.Error()
			return
		}
		audioData = append(audioData, d...)
	}

	// 文件名称
	filename := filepath.Join("cache", fmt.Sprintf("output-%d.wav", time.Now().UnixMilli()))
	T.resultData["wav"] = filename

	// 转为wav
	audio := tools.Audio{WavFileName: filename}
	_ = audio.AddWavHeader(audioData, 1, 16000, 16)

	// 播放音频
	if T.isPlay {
		_ = audio.PlayWav()
	}
}

func (T *TTStudio) Result() map[string]any {
	return maps.Clone(T.resultData)
}
